package com.example.java_gobang.api;

import com.example.java_gobang.game.MatchRequest;
import com.example.java_gobang.game.MatchResponse;
import com.example.java_gobang.game.Matcher;
import com.example.java_gobang.game.OnlineUserManager;
import com.example.java_gobang.model.User;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

@Slf4j
@Component
public class MatchAPI extends TextWebSocketHandler {
    //后面处理，字符串使用。
    @Autowired
    ObjectMapper objectMapper;

    @Autowired
    OnlineUserManager onlineUserManager;

    @Autowired
    Matcher matcher;

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        //WebSocketConfig 中加入了 Interceptor 才能拿到 httpsession 中的 session 信息。
        MatchResponse matchResponse = new MatchResponse();
        try {
            User user = (User) session.getAttributes().get("user");
            log.info("用户{} 进入游戏大厅",user.getUserName());
            if (onlineUserManager.getFromGameHall(user.getUserId()) != null ||
                    onlineUserManager.getFromGameRoom(user.getUserId()) != null) {  //多开问题处理

                matchResponse.setOk(true);
                matchResponse.setReason("禁止多开");
                //告诉客户端，这里重复登录了。
                matchResponse.setMessage("repeatConnection");
                session.sendMessage(new TextMessage(objectMapper.writeValueAsString(matchResponse)));
                //断开重复的连接
                //不适用了，去掉
                //session.close(); //会触发 afterConnectionClosed()
                return;
            }
            onlineUserManager.enterGameHall(user.getUserId(),session);
            log.info("用户{} 进入游戏大厅成功",user.getUserName());
        } catch (NullPointerException e) {//user.getUserId() 存在空指针问题，没有拦截器，若直接访问 游戏大厅页面，则无用户信息。
            //对空指针问题处理
            e.printStackTrace();
            matchResponse.setOk(true);
            matchResponse.setReason("未登录");
            matchResponse.setMessage("notLoggedIn");
            session.sendMessage(new TextMessage(objectMapper.writeValueAsString(matchResponse)));
        }


    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        // 接受客户端发送的消息
        String payload = message.getPayload();
        // JSON 字符串，转换为 Java 对象
        MatchRequest matchRequest = objectMapper.readValue(payload, MatchRequest.class);
        log.info(matchRequest.getMessage());
        MatchResponse response = new MatchResponse();
        User user = (User) session.getAttributes().get("user");
        if (matchRequest.getMessage().equals("startMatch")) {
            matcher.add(user);
            response.setOk(true);
            response.setMessage("startMatch");
        } else if (matchRequest.getMessage().equals("stopMatch")) {

            matcher.remove(user);
            response.setOk(true);
            response.setMessage("stopMatch");
        } else {

            response.setOk(true);
            response.setReason("非法匹配请求");
        }
        String jsonStr = objectMapper.writeValueAsString(response);
        session.sendMessage(new TextMessage(jsonStr));
    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        User user = (User) session.getAttributes().get("user");
        log.info("用户{} 退出游戏大厅",user.getUserName());
        try {

            WebSocketSession tmpSession = onlineUserManager.getFromGameHall(user.getUserId());
            if (tmpSession == session) {  //多开问题处理
                onlineUserManager.existGameHall(user.getUserId());
            }
            //匹配中，连接关闭，移出队列
            matcher.remove(user);
        } catch (NullPointerException e) {
//            e.printStackTrace();
            log.info("[MatchAPI] afterConnectionClosed 当前用户未登录");

            //处理草率了，已经断开了连接，不需要再发送消息了。

//            MatchResponse matchResponse = new MatchResponse();
//            matchResponse.setOk(true);
//            matchResponse.setReason("未登录");
//            matchResponse.setMessage("notLoggedIn");
//            session.sendMessage(new TextMessage(objectMapper.writeValueAsString(matchResponse)));
        }
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        User user = (User) session.getAttributes().get("user");
        log.info("用户{} 退出游戏大厅",user.getUserName());
        try {
            WebSocketSession tmpSession = onlineUserManager.getFromGameHall(user.getUserId());
            if (tmpSession == session) {  //多开问题处理
                onlineUserManager.existGameHall(user.getUserId());
            }
            //匹配中，连接关闭，移出队列
            matcher.remove(user);
        } catch (NullPointerException e) {
//            e.printStackTrace();
            log.info("[MatchAPI] afterConnectionClosed 当前用户未登录");


            //处理草率了，已经断开了连接，不需要再发送消息了。

//            MatchResponse matchResponse = new MatchResponse();
//            matchResponse.setOk(true);
//            matchResponse.setReason("notLoggedIn");
//            session.sendMessage(new TextMessage(objectMapper.writeValueAsString(matchResponse)));
        }
    }
}
